<script setup lang="ts">

defineOptions({name: 'UserRoleAllocation'})
import {getIsMobile, delObjEmptyVal, listToLabelValueOptions} from "@/utils/helper"
import {useI18n} from "vue-i18n"
import {getUserRoleList, settingUserRole} from '@/api/user-role'
import {getRoleList} from '@/api/role'

const dataId = ref<number | string>(0)
const formRef = ref()
const visible = ref<boolean>(false)
const disabledSubmit = ref<boolean>(false)
const isMobile = getIsMobile()
const {t} = useI18n()
const formItems = ref<any>([
	{
		key: 'roleIds', type: 'select', placeholder: t('common.selectPlaceholder'), span: 24,
		props: {options: [], multiple: true, clearable: true}
	}
])

const formData = ref<any>({roleIds: []})

interface emits {
	(e: 'success', params: Record<string, any>): void
}

interface Props {
	enumData?: Record<string, any>
	languageData?: Record<string, any>
}

defineProps<Props>()
const emit = defineEmits<emits>()

const handleSubmit = async () => {
	await formRef.value.validate()
	if (disabledSubmit.value) return false
	disabledSubmit.value = true
	try {
		const sendData = {...formData.value}
		delObjEmptyVal(sendData)
		sendData.userId = dataId.value
		const res: any = await settingUserRole(sendData)
		emit('success', res)
		setTimeout(() => {
			close()
		}, 600)
	} catch (error) {
		console.error('[UserUpdatePassword] Unexpected error:', error)
	} finally {
		setTimeout(() => {
			disabledSubmit.value = false
		}, 800);
	}
}

const getData = async () => {
	const getRoleRes: any = await getRoleList({page: 1, limit: 1000, fields: ['roleId', 'name']})
	formItems.value[0].props.options = listToLabelValueOptions(getRoleRes.list, 'name', 'roleId')
	const getUserRoleRes: any = await getUserRoleList({page: 1, limit: 1000, userId: dataId.value, fields: ['roleId']})
	const roleIds = getUserRoleRes.list.map((item: any) => item.roleId)
	Object.assign(formData.value, {roleIds: roleIds})
}

const open = (id: any) => {
	visible.value = true
	dataId.value = id
	getData()
}

const close = () => {
	formRef.value.reset()
	visible.value = false
}

defineExpose({open, close})
</script>

<template>
	<div class="form-operate-box">
		<ElDialog
			v-model="visible" :title="t('module.user.operate.roleAllocation')" :width="isMobile ? '100%' : '500px'"
			@close="close" :close-on-click-modal="false" :align-center="true" :draggable="true"
		>
			<ArtForm ref="formRef" labelPosition="top" v-model="formData" :items="formItems"
				:disabledSubmit="disabledSubmit" :showReset="false"
				@close="close" @submit="handleSubmit"/>
		</ElDialog>
	</div>
</template>

<style scoped lang="scss">
.form-operate-box {
	:deep(.el-form-item--label-top .el-form-item__label) {
		margin-left: 3px !important;
		margin-bottom: 2px !important;
	}
	:deep(.el-dialog__body) {
		padding: 0 !important;
	}
	:deep(.action-buttons-wrapper) {
		margin-top: 8px !important;
		justify-content: flex-end !important;
	}
}
</style>